package com.lw.config;

import com.lw.config.util.DroolsUtil;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.utils.KieHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.List;

/**
 * 初始化Spring容器时加载规则drl到容器中
 */
@Configuration
public class KiaSessionConfig {

    private static final String RULES_PATH = "rules/";

    @Bean
    public KieFileSystem kieFileSystem() throws IOException {
        // KieFileSystem 是一个内存文件系统，用于以编程方式定义, 组成 KieModule 的资源
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        for (Resource file : getRuleFiles()) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));
        }
        return kieFileSystem;
    }

    private Resource[] getRuleFiles() throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        final Resource[] resources = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
        return resources;
    }

    @Bean
    public KieContainer kieContainer() throws IOException {

        final KieRepository kieRepository = getKieServices().getRepository();
        kieRepository.addKieModule(new KieModule() {
            public ReleaseId getReleaseId() {
                return kieRepository.getDefaultReleaseId();
            }
        });
        // 解析drl文件内容并构建规则
        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());

    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }

    // 将ftl动态生成的规则存储到数据库时，用于初始化加载全部规则
    @Bean
    public KieBase kieBase() {
        /**
         * KieBase 是所有应用程序知识定义的存储库。
         * 它将包含规则、流程、功能、类型模型。
         * KieBase 本身不包含运行时数据，而是从 KieBase 创建会话可以在其中插入数据并启动流程实例。
         */
        KieBase kieBase = getKieServices().getKieClasspathContainer().getKieBase();

        // 查询出所有规则
//        List<Rule> rules = ruleMapper.selectAll();
//        // 分别编译（分别处理编译错误）
//        rules.forEach(item ->
//                DroolsUtil.buildRule(kieBase, item.getName(), item.getDefinition())
//        );

        return kieBase;
    }
    // 注册到bean中，方便自动装配直接使用
    @Bean
    public KieSession kieSession() throws IOException {
        // 为这个 KieContainer 创建默认的 KieSession
        return kieContainer().newKieSession();
    }
}